//
//  MujiDubPreviewViewController.m
//  testdemo
//
//  Created by yule on 2017/5/24.
//  Copyright © 2017年 yule. All rights reserved.
//

#import "MujiDubPreviewViewController.h"
#import "MujiDubFilePathUtility.h"
#import "DownLoadManager.h"
#import "SSZipArchive.h"
#import "MujiAudioComposition.h"
#import "ContentManager.h"
#import "MujiDubDialogLinesModel.h"

@interface MujiDubPreviewViewController () <DownLoadDelegate, SSZipArchiveDelegate>

//总句子数
@property (nonatomic, assign) int   totalDialogs;

@property (nonatomic, strong) NSMutableArray* metaArray;


@end

@implementation MujiDubPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.videoUrl = [NSString stringWithFormat:@"http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo.mp4"];
    
    self.metaArray = [[NSMutableArray alloc] init];

    self.userId = @"1670";
    self.dialogId = @"123456";
    self.totalDialogs = 7;
    
    
    
    [self downloadRecordFile];

    
}

//  下载录音zip 解压并合成整段
- (void)downloadRecordFile
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *outError = nil;
    NSString *userDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *name = [NSString stringWithFormat:@"%@_%@", self.userId, self.dialogId];
    
    NSString *downloadRecordCache = [userDocumentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"MujiDownloadRecordCache/DataCache/%@", name]];

    if ([fileManager fileExistsAtPath:downloadRecordCache]) {
        
        //[fileManager removeItemAtPath:downloadRecordCache error:nil];
        
    }else {
        
        if ([fileManager createDirectoryAtPath:downloadRecordCache withIntermediateDirectories:YES attributes:nil error:&outError]) {
            
        }else {
            return;
        }
    }
    
    NSString *path = [userDocumentsDirectory stringByAppendingPathComponent:@"MujiDownloadRecordCache/DataCache"];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.zip", self.userId, self.dialogId];

    NSString *filePath = [path stringByAppendingPathComponent:fileName];

    if ([fileManager fileExistsAtPath:filePath]) {
        
        [fileManager removeItemAtPath:filePath error:nil];
    }

    //  压缩文件 url
    NSString *zipUrl = @"http://gearedu.oss-cn-shenzhen.aliyuncs.com/1670_123456.zip";
    
    [[DownLoadManager shared] selectDownLoadBtn:self with:filePath with:zipUrl];
}
#pragma mark -- DownloadDelegate
// 下载完成
- (void)downloadFinish:(NSString *)path
{
    NSString *libaryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *bufferPath = [libaryPath stringByAppendingPathComponent:@"MujiDownloadRecordCache/DataCache"];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.zip", self.userId, self.dialogId];

    NSLog(@"-------%@", path);
    if (![[NSFileManager defaultManager] fileExistsAtPath:bufferPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:bufferPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *existPath = [bufferPath stringByAppendingPathComponent:fileName];
    
    NSString *name = [NSString stringWithFormat:@"%@_%@", self.userId, self.dialogId];
    
    NSString *sectionDataPath = [libaryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"MujiDownloadRecordCache/DataCache/%@/sectionData", name]];

//    if (![[NSFileManager defaultManager] fileExistsAtPath:sectionDataPath]) {
//        [[NSFileManager defaultManager] createDirectoryAtPath:sectionDataPath withIntermediateDirectories:YES attributes:nil error:nil];
//    }
    NSLog(@"%@", sectionDataPath);
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:sectionDataPath]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [SSZipArchive unzipFileAtPath:path toDestination:sectionDataPath delegate:self];
        });
    }else {
        [[NSFileManager defaultManager] removeItemAtPath:sectionDataPath error:nil];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [SSZipArchive unzipFileAtPath:path toDestination:sectionDataPath delegate:self];
        });
    }
}
#pragma mark -- SSZipArchiveDelegate
// 解压进度
- (void)zipArchiveProgressEvent:(unsigned long long)loaded total:(unsigned long long)total
{
    NSLog(@"%lld    %lld",loaded,total);
    if (loaded == total) {//  解压完成
        [self mergeRecordData];
    }
}

//合成录音
- (void)mergeRecordData
{
    NSString *userId = self.userId;
    
    NSString *libaryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *bufferPath = [libaryPath stringByAppendingPathComponent:@"MujiDownloadRecordCache/DataCache"];
    NSString *userAudioDirectory = [bufferPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@/sectionData", self.userId, self.dialogId]];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *files = [manager subpathsAtPath:userAudioDirectory];
    
    NSLog(@"%@", files);
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [files sortedArrayUsingComparator:sort];
    NSLog(@"字符串数组排序结果%@",resultArray);
    
    if (resultArray.count != self.totalDialogs) {//  音频数量跟踪句子数量不同
        return;
    }
    NSMutableArray *sourceURLs = [NSMutableArray arrayWithCapacity:10];
    for (NSString *fileName in resultArray) {
        NSString *filePath = [userAudioDirectory stringByAppendingPathComponent:fileName];
        [sourceURLs addObject:[NSURL fileURLWithPath:filePath]];
    }
    
    userAudioDirectory = [bufferPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@", userId, self.dialogId]];
    
    NSString *mergeDataFileName = [NSString stringWithFormat:@"%@_%@.mp4", self.userId, self.dialogId];
    NSError *outError = nil;
    
    if ([manager fileExistsAtPath:[userAudioDirectory stringByAppendingString:mergeDataFileName]])
    {
        //return YES;
        //[_mutablePaths setObject:userAudio forKey:@(MujiDubFilePathDirectoryUserAudio)];
    }
    else
    {
        if ([manager createDirectoryAtPath:userAudioDirectory withIntermediateDirectories:YES attributes:nil error:&outError])
        {
        }else {
            return;
        }
    }
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",
                          userId,
                          self.dialogId];
    NSString *path = [userAudioDirectory stringByAppendingPathComponent:fileName];
    
    ContentManager * __weak weakContentManager =  [ContentManager sharedManager];
    
    [weakContentManager getDialogCompleteMetaDataWithID:self.dialogId success:^(id content) {
        //return;
        if (content == nil) {
            return;
        }
        //self.slowSpeakAudioURL = [NSURL URLWithString:dialogContent[@"slowSpeakAudioURL"]];
        
        //self.duration = dialogContent[@"duration"];
#if 1
        if (content) {
            for (id obj in content) {
                
                MujiDubDialogLinesModel *dialogLinesModel = [[MujiDubDialogLinesModel alloc] init];
                [dialogLinesModel setValuesForKeysWithDictionary:obj];
                dialogLinesModel.dialogId = self.dialogId;
                
                dialogLinesModel.cueEnd = dialogLinesModel.curEnd;
                dialogLinesModel.cueStart = dialogLinesModel.curStart;
                
                dialogLinesModel.dialogLineID = [NSString stringWithFormat:@"%d", (int)[content indexOfObject:obj] + 1];
                
                [self.metaArray addObject:dialogLinesModel];
                
                if (self.metaArray.count == 0) {
                    return;
                }
            }
        }
#endif
        [MujiAudioComposition sourceURLs:sourceURLs dialogs:self.metaArray composeToURL:[NSURL fileURLWithPath:path] completed:^(NSError *error) {
            
            //  合成录音完成
            
            
        }];
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)backAction
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
